package com.example;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import java.util.ArrayList;
import java.util.List;

@Controller
@SpringBootApplication
public class SpringCoalApplication {

	@Autowired
	private Entry entry;

	public static void main(String[] args) {
		SpringApplication.run(SpringCoalApplication.class, args);
	}

	@GetMapping("/")
	public String index(Model model) {
		model.addAttribute("allCollieries", entry.getAll());
		model.addAttribute("colliery", new Colliery());
		return "data";
	}

	@PostMapping("/colliery")
	public String addColliery(@ModelAttribute Colliery colliery) {
		entry.save(colliery);
		return "redirect:";
	}
}



@Component
class Entry implements CommandLineRunner{

	private final CollieryRepository repository;

	@Autowired
	public Entry(CollieryRepository repository){
		this.repository = repository;
	}

	@Override
	public void run(String... strings) throws Exception {

		List<Colliery> list = repository.findAll();
		for (Colliery colliery : list) {
			System.out.println(colliery);
		}
	}

	public List<Colliery> getAll() {
		return repository.findAll();
	}

	public void save(Colliery colliery) {
		repository.save(colliery);
	}
}

interface CollieryRepository extends JpaRepository<Colliery, Long> {
}